<?php

/**
 * Description of WebservicePrecarite
 *
 * @author bonfiglio
 * @todo Commenter !!!
 */
class WebservicePrecarite extends WebserviceBase {

    public function answer() {
        if ($this->name == 'get-waiting-contacts') {
            $Database = Database::factory();
            $sql = 'SELECT * FROM front.forms WHERE formName IN (:form_full,:form_lead) AND status = :status;';

            $Result = new Result($Database->execute($sql, array(':status' => $this->post['status'], ':form_full' => FormPrecarite::$FORM_FULL_NAME, ':form_lead' => FormPrecarite::$FORM_LEAD_NAME)));

            //Génération du résultat
            $content = '';
            $after = '';
            if ($Result->Count()) {

                $datasToken = array('date_expired' => strtotime("+1 week"), 'data' => array());
                $FormPrecarite = new FormPrecarite();
                $forms = $FormPrecarite->getOptions();

                while ($data = $Result->fetch()) {
                    $datasToken['data'][] = $data['id'];
                    $fields = $forms[$data['formName']];                    
                    $fields['id'] = array();
                    $content .= HtmlTag::lead($this->setXmlContent($fields, $data, FormPrecarite::$FIELDS_MATCH_4D));
                }
                $Token = new Token();
                $Token->generate($datasToken);
                $after = HtmlTag::token($Token->token);
            }
            $content = HtmlTag::leadsprecarite($content . $after);
        } else {
            //vérification de validité des données
            $Token = new Token($this->post['token']);
            if (!$Token->error) {
                $ids = array_unique(array_filter(explode(',', $this->post['ids'])));
                $data = $Token->getData();
                $diff = array_intersect($ids, $data);
                if (!count($diff)) {
                    $content = HtmlTag::error(HtmlTag::message('Valeurs (ids : '.  implode(', ', $ids).') invalides'));
                } else {
                    $ids = implode(',',$diff);
                    $sql = 'UPDATE forms SET status = 1 WHERE id IN ('.$ids.');';
                    $Database = Database::factory();
                    $Result = new Result($Database->execute($sql));
                    $content = HtmlTag::success(HtmlTag::ids($ids));
                    $Token->incrementUseMeter();
                }
            } else {
                $content = HtmlTag::error(HtmlTag::message($Token->error));
            }
        }
        $this->sendContent($content);
    }

}

?>
